import React, { useState, useEffect, useMemo } from "react";
import "./index.scss";
import { useLocation, useHistory } from "react-router-dom";
import { Menu } from "antd";
import VisitorRouter from "../../router/RenderRouter/visitor";
import AdminRouter from "../../router/RenderRouter/admin";
const { SubMenu } = Menu;
const MenuCom = () => {
  const location = useLocation();
  const history = useHistory();
  const userData = window.sessionStorage.getItem("userData");
  const [pathname, setPathname] = useState(location.pathname);
  const [role, setRole] = useState("");
  useEffect(() => {
    if (userData) {
      setRole(JSON.parse(userData).identity);
    } else {
      setRole("访客");
    }
  }, []);
  useMemo(() => {
    setPathname(location.pathname);
  }, [location.pathname]);
  //点击菜单操作
  const handlerClick = (item) => {
    history.push(item.key); //跳转对应路由
  };
  return (
    <Menu theme="dark" mode="inline" defaultSelectedKeys={pathname}>
      {MenuChildrenCom(role === "管理员" ? AdminRouter : VisitorRouter, handlerClick)}
    </Menu>
  );
};
export default MenuCom;

const MenuChildrenCom = (routes, handlerClick) => {
  return (
    <>
      {routes?.length &&
        routes.map((item) => {
          return item.children ? (
            <SubMenu key={item.path} icon={<i className={`iconfont ${item.icon}`} />} title={item.title}>
              {item.children.length &&
                item.children.map((val) => {
                  return (
                    <Menu.Item onClick={handlerClick} key={val.path} icon={<i className={`iconfont ${val.icon}`} />}>
                      {val.title}
                    </Menu.Item>
                  );
                })}
            </SubMenu>
          ) : (
            <Menu.Item onClick={handlerClick} key={item.path} icon={<i className={`iconfont ${item.icon}`} />}>
              {item.title}
            </Menu.Item>
          );
        })}
    </>
  );
};
